package com.smartview.common.xss;

public class XSSEncoder {
	static public String encode(String fragment)
	{
		// If the input is null, then the output is null
		if (fragment == null) return null;
		
		StringBuffer builder = new StringBuffer(fragment.length() + 10); // a little wiggle room
		char[] characters = fragment.toCharArray();
		
		// This loop used to also look for and replace single ticks with &apos; but it
		// turns out that it's not strictly necessary since Stripes uses double-quotes
		// around all form fields, and stupid IE6 will render &apos; verbatim instead
		// of as a single quote.
		for (int i=0; i<characters.length; ++i) {
		    switch (characters[i]) {
		        case '<'  : builder.append("&lt;"); break;
		        case '>'  : builder.append("&gt;"); break;
		        case '"'  : builder.append("&quot;"); break;
		        case '&'  : builder.append("&amp;"); break;
		        default: builder.append(characters[i]);
		    }
		}
		
		return builder.toString();
	}

	public static String[] encode(String[] fragments) {
		
		String[] encodedList = new String[fragments.length];
		for(int i = 0 ; i < fragments.length ; i++)
		{
			encodedList[i] = new String(encode(fragments[i]));
		}		
		return encodedList;
	}
}
